package com.xuanwu.ai.flow.config;

import com.alibaba.fastjson.JSONObject;
import com.xuanwu.ai.core.exception.DataAccessException;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.utils.JwtUtil;
import com.xuanwu.ai.flow.utils.ThreadSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/component/**", "/flowData/**", "/manage/**", "/tenant/**", "/ai/**")
                .excludePathPatterns("/auth/login");
    }

    static class TokenInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String token = request.getServletPath().startsWith("/ai") ? request.getHeader("token") : request.getHeader("plattoken");
            String flag = request.getServletPath().startsWith("/ai") ? GlobalConstant.FLOW_UNWRAP_FLAG : GlobalConstant.PLATFORM_UNWRAP_FLAG;
            log.info(token);
            try {
                ThreadSessionUtil.set(JwtUtil.unwrap(token, flag));
            } catch (DataAccessException e) {
                postInterceptor(response, "jwt token无效");
                return false;
            }

            return true;
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            ThreadSessionUtil.remove();
        }

        protected void postInterceptor(HttpServletResponse response, String message) throws Exception {
            log.error(message);
            // 如果被拦截，返回信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //响应内容
            JSONObject responseMsg = new JSONObject();
            responseMsg.put("message", HttpStatus.UNAUTHORIZED.getReasonPhrase());
            response.getWriter().println(responseMsg.toJSONString());
        }
    }
}
